<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>购物车管理页面</title>
		<!-- 1. 先加载Vue核心库 -->
		<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

		<!-- 2. 加载Element UI样式 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

		<!-- 3. 加载Element UI组件库 -->
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>

		<!-- 4. 加载axios -->
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

		<!-- 5. 最后加载自定义JS -->
		<script src="../js/common.js"></script>
		<script src="../js/authChecker.js"></script>

		<!-- 移除重复的库引用 -->
		<!-- 删除以下重复引用 -->
		<!-- <script src="../js/vue.js"></script> -->
		<!-- <script src="../js/elementui.js"></script> -->
		<!-- <script src="../js/axios.min.js"></script> -->

		<!-- 引入自定义样式 -->
		<link rel="stylesheet" href="../css/categroy/categroy.css">
	</head>
	<body>
		<div id="app">
			<div class="page-title">购物车管理</div>
			<el-row>
				<el-col :span="6">
					<el-input style="display:inline" v-model="searchKey" placeholder="请输入用户名称或蛋糕名称"
						clearable></el-input>
				</el-col>
				<el-button @click="onSearch" type="primary" class="purple-search-btn">搜索</el-button>
				<el-button @click="resetSearch" type="info" plain>重置</el-button>
			</el-row>

			<el-table :data="buycarList" style="width: 1400px" height="550"
				:header-cell-style="{background:'#f2f2f2', color:'#606266'}" v-loading="loading">
				<el-table-column prop="buyId" label="购物车编号" width="150" fixed></el-table-column>
				<el-table-column prop="userName" label="用户名称" width="200" fixed></el-table-column>
				<el-table-column prop="cakeName" label="蛋糕名称" width="200"></el-table-column>
				<el-table-column prop="cakeSum" label="数量" width="100"></el-table-column>
				<el-table-column prop="cakeSizeType" label="尺寸类型" width="120">
					<template slot-scope="scope">
						{{ scope.row.cakeSizeType === 0 ? '4寸' : '6寸' }}
					</template>
				</el-table-column>
				<el-table-column prop="cakePrice" label="单价" width="120">
					<template slot-scope="scope">
						￥{{
									scope.row.cakePrice !== undefined && 
									!isNaN(scope.row.cakePrice) 
										? scope.row.cakePrice.toFixed(2) 
										: '0.00' 
								}}
					</template>
				</el-table-column>
				<el-table-column prop="totalPrice" label="总价" width="120">
					<template slot-scope="scope">
						￥{{
									(scope.row.cakePrice !== undefined && !isNaN(scope.row.cakePrice) &&
									 scope.row.cakeSum !== undefined && !isNaN(scope.row.cakeSum))
										? (scope.row.cakePrice * scope.row.cakeSum).toFixed(2)
										: '0.00'
								}}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="200" fixed="right">
					<template slot-scope="scope">
						<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)"
							class="cate-del-btn">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<el-pagination style="margin-left: 500px;" background layout="prev, pager, next" :total="total"
				:page-size="pageSize" :current-page="currentPage" @current-change="currentChange">
			</el-pagination>
		</div>

		<script>
			// 在页面加载时立即检查登录状态
			if (!checkAdminLogin()) {
				// 登录检查失败，阻止页面继续加载
				console.log('登录验证失败，已跳转至登录页');
			} else {
				new Vue({
					el: "#app",
					data: {
						searchKey: '', // 搜索关键词
						buycarList: [], // 购物车列表数据
						userList: [], // 用户列表
						cakeList: [], // 蛋糕列表
						total: 0, // 总记录数
						pageSize: 5, // 每页显示数量
						currentPage: 1, // 当前页码
						loading: false, // 加载状态
						dialogAddVisible: false, // 新增对话框显示状态
						dialogEditVisible: false, // 编辑对话框显示状态
						newBuycar: { // 新增购物车数据
							userId: null,
							cakeId: null,
							cakeSizeType: 0,
							cakeSum: 1,
							cakePrice: null
						},
					},
					methods: {
						// 加载购物车列表
						loadBuycars() {
							this.loading = true;
							let apiUrl = API + 'buycar/selectBuycarDetails';
							let params = {
								page: this.currentPage,
								pageSize: this.pageSize
							};

							// 如果有搜索关键词，使用搜索接口
							if (this.searchKey && this.searchKey.trim() !== '') {
								apiUrl = API + 'buycar/selectBuycarDetailsBySearch';
								params.searchKey = this.searchKey;
							}

							axios.get(apiUrl, {
									params
								})
								.then(response => {
									if (response.data.code === 200) {
										const data = response.data.data;
										const pageInfo = data.buycarPageInfo || data;

										this.buycarList = pageInfo.list.map(item => ({
											...item,
											cakePrice: Number(item.cakePrice) || 0,
											cakeSum: Number(item.cakeSum) || 0
										}));
										this.total = pageInfo.total;

										console.log('加载购物车数据成功:', {
											currentPage: this.currentPage,
											total: this.total,
											pageSize: this.pageSize,
											listLength: this.buycarList.length
										});
									} else {
										this.$message.error(response.data.message || '获取购物车列表失败');
									}
								})
								.catch(error => {
									console.error('加载购物车数据失败:', error);
									this.$message.error('加载购物车数据失败，请稍后重试');
								})
								.finally(() => {
									this.loading = false;
								});
						},

						// 搜索
						onSearch() {
							this.currentPage = 1; // 搜索时重置为第一页
							this.loadBuycars();
						},

						// 重置搜索
						resetSearch() {
							this.searchKey = '';
							this.currentPage = 1;
							this.loadBuycars();
						},

						// 分页变化
						currentChange(page) {
							this.currentPage = page;
							this.loadBuycars();
						},

						// 加载用户列表
						loadUsers() {
							axios.get(API + 'user/getUserList')
								.then(response => {
									if (response.data.code === 200) {
										this.userList = response.data.data;
									} else {
										this.$message.error('获取用户列表失败：' + response.data.message);
									}
								})
								.catch(error => {
									console.error('请求出错：', error);
								});
						},

						// 加载蛋糕列表
						loadCakes() {
							axios.get(API + 'cake/getCakeList')
								.then(response => {
									if (response.data.code === 200) {
										this.cakeList = response.data.data;
									} else {
										this.$message.error('获取蛋糕列表失败：' + response.data.message);
									}
								})
								.catch(error => {
									console.error('请求出错：', error);
								});
						},

						// 显示新增对话框
						showAddDialog() {
							this.dialogAddVisible = true;
							this.newBuycar = {
								userId: null,
								cakeId: null,
								cakeSizeType: 0,
								cakeSum: 1,
								cakePrice: null
							};
							if (this.$refs.newBuycarForm) {
								this.$refs.newBuycarForm.resetFields();
							}
						},

						// 蛋糕选择变化
						handleCakeChange(cakeId) {
							const selectedCake = this.cakeList.find(cake => cake.cakeId === cakeId);
							if (selectedCake) {
								this.newBuycar.cakePrice = this.newBuycar.cakeSizeType === 0 ?
									Number(selectedCake.cakePrice) || 0 :
									Number(selectedCake.cakePricebig) || 0;
							}
						},

						// 处理删除按钮点击
						handleDelete(index, row) {
							this.$confirm('确定删除该购物车记录吗？', '提示', {
									type: 'warning'
								})
								.then(() => {
									this.loading = true;
									axios.delete(`${API}buycar/${row.buyId}`)
										.then(response => {
											if (response.data.code === 200) {
												this.$message.success('删除成功');
												this.loadBuycars();
											} else {
												this.$message.error(response.data.message || '删除失败');
											}
										})
										.catch(error => {
											console.error('删除出错:', error);
											this.$message.error('删除失败，请稍后重试');
										})
										.finally(() => {
											this.loading = false;
										});
								})
								.catch(() => {
									this.$message.info('已取消删除');
								});
						}
					},
					watch: {
						'newBuycar.cakeSizeType'(newVal) {
							if (this.newBuycar.cakeId) {
								const selectedCake = this.cakeList.find(cake => cake.cakeId === this.newBuycar.cakeId);
								if (selectedCake) {
									this.newBuycar.cakePrice = newVal === 0 ?
										Number(selectedCake.cakePrice) || 0 :
										Number(selectedCake.cakePricebig) || 0;
								}
							}
						}
					},
					mounted() {
						this.loadBuycars();
						this.loadUsers();
						this.loadCakes();
					}
				});
			}
		</script>
	</body>
</html>